﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace FtpInfras;
public class FtpUtil : IFtpUtil
{
    public void PassiveUpLoad(string file)
    {
        Console.ForegroundColor = ConsoleColor.DarkGreen;
        var ftpServerUrl = "ftp://192.168.231.131/cc-demo.nii.gz";

        var filePath = @"D:\TempDicoms\cc-demo.nii.gz";

        // Create an FtpWebRequest object
        var request = (FtpWebRequest)WebRequest.Create(ftpServerUrl);

        // Set the request method to upload a file
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // Set the credentials
        request.Credentials = new NetworkCredential("ftpuser", "19941008");

        // Enable passive mode
        request.UsePassive = true;

        // Copy the contents of the file to the request stream
        byte[] fileContents = ReadFileToByteArray(filePath);

        request.ContentLength = fileContents.Length;

        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        // Get the response from the FTP server
        using (var response = (FtpWebResponse)request.GetResponse())
        {
            Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="file"></param>
    public void ActiveUpLoad(string file)
    {
        Console.ForegroundColor = ConsoleColor.DarkGreen;
        //var ftpServerUrl = "ftp://192.168.31.116/chenchang/";
        string ftpServerUrl = "ftp://192.168.126.129/";
        var userName = "ftpuser";
        var password = "19941008";

        var sourceFilePath = @"D:\Hr\WorkSpace\search-hr\Search-Hr\ConsoleApp1\bin\x64\Debug\net6.0\chenchang.nii.gz";
        var destinationFileName = "chenchang.nii.gz"; // 远程服务器上的文件名

        // 创建 FileInfo 对象
        var fileInfo = new FileInfo(sourceFilePath);

        if (fileInfo.Exists)
        {
            var fileSizeInBytes = fileInfo.Length;
            Console.WriteLine($"File size: {fileSizeInBytes / (1024.0 * 1024.0)} MB"); // 转换为 MB
        }

        // 创建FTP请求
        var request = (FtpWebRequest)WebRequest.Create(ftpServerUrl + destinationFileName);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential(userName, password);

        var sp = Stopwatch.StartNew();
        sp.Start();
        // 读取本地文件并上传到FTP服务器
        using (var fileStream = File.OpenRead(sourceFilePath))
        using (var ftpStream = request.GetRequestStream())
        {
            var buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ftpStream.Write(buffer, 0, bytesRead);
            }
        }
        sp.Stop();

        // 显示上传成功信息
        Console.WriteLine($"File uploaded successfully to {ftpServerUrl}, consume time :{sp.ElapsedMilliseconds}");
    }

    public void DownloadFile(string savePath)
    {
        //var ftpServerUrl = "ftp://192.168.31.116/chenchang/";
        var ftpServer = "ftp://192.168.231.131/cc-demo.nii.gz";
        var username = "ftpuser";
        var password = "19941008";

        var localFile = "cc-demo.nii.gz";

        // 创建 FtpWebRequest 对象
        var request = (FtpWebRequest)WebRequest.Create(ftpServer);
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        request.Credentials = new NetworkCredential(username, password);

        // 获取 FtpWebResponse 对象
        using FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        using Stream responseStream = response.GetResponseStream();
        using FileStream fileStream = new FileStream(localFile, FileMode.Create);
        var buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fileStream.Write(buffer, 0, bytesRead);
        }

        Console.WriteLine($"Download Complete, status {response.StatusDescription}");

    }


    byte[] ReadFileToByteArray(string filePath)
    {
        // 检查文件是否存在
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException($"File not found: {filePath}");
        }

        // 使用 FileStream 读取文件
        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            // 使用 MemoryStream 将 FileStream 转换为字节数组
            using (MemoryStream memoryStream = new MemoryStream())
            {
                fileStream.CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }
    }

}
